/**
* @Author: 李晨光
* @Date: 2019/12/17
* @Version: 1.0
* @Last Modified by: 李晨光
* @Last Modified time: 2019/12/17
**/
<comment>
  # 组件注释
</comment>
<template>
  <div id="DataAnalyze" class="p-box">
    <div class="p-return">
      <mu-appbar color="primary" class="lan-header">
        <mu-button icon slot="left" v-close>
          <i class="iconfont angle-left iconangle-left"></i>
        </mu-button>数据分析
      </mu-appbar>
      <mTabs v-model="active" :tabList="tabList" @change="tabStatus" style="z-index: unset" />
    </div>
    <div class="select-box">
      <span class="org-select" v-if="active == 1" @click="open">
        {{ currOrg }}
        <i class="iconfont iconsort-down" style="color: #8C8C8C;"></i>
      </span>
      <div class="ly_flex">
        <mu-date-input
          v-model="params.startTime"
          placeholder="请选择开始日期"
          class="date-select"
          @change="getData"
          value-format="YYYY-MM-DD"
          :should-disable-date="disabledStartDates"
          container="bottomSheet"
        >
          <i class="iconfont iconsort-down" style="color: #8C8C8C;"></i>
        </mu-date-input>
        <span style="font-size: .2rem;padding: 0 10px;">-</span>
        <mu-date-input
          v-model="params.endTime"
          placeholder="请选择结束日期"
          class="date-select"
          @change="getData"
          :should-disable-date="disabledEndDates"
          value-format="YYYY-MM-DD"
          container="bottomSheet"
        >
          <i class="iconfont iconsort-down" style="color: #8C8C8C;"></i>
        </mu-date-input>
      </div>
    </div>
    <div style="height:calc(100vh - .45rem - .5rem);overflow: auto;background: #fff">
      <canvas id="container"></canvas>
    </div>
    <!-- 选项目 -->
    <Org
      ref="org"
      v-if="org.open"
      :open="org.open"
      @close="close"
      v-model="org.res"
      @confirm="confirm"
    ></Org>
  </div>
</template>

<script>
import F2 from "@antv/f2";
const PieLabel = require("@antv/f2/lib/plugin/pie-label");
import mTabs from "@/tabs/mTabs";
import Org from "@/select/org/Org.vue";
export default {
  name: "DataAnalyze",
  components: {
    mTabs,
    Org
  },
  props: {},
  data() {
    return {
      api: {
        getObsDataApi: "/safety/starObserve/pie", // 行为观察数据分析
        getIssRepoDataApi: "/safety/problemReport/pie" // 行为观察数据分析
      },
      tabList: [{ id: "1", name: "行为观察" }, { id: "2", name: "问题上报" }],
      active: "1",
      chart: null,
      chartData: [],
      currOrg: "",
      org: {
        open: false,
        res: []
      },
      params: {
        orgId: "", // 项目id
        type: "", // 组织类别
        startTime: null, // 开始时间
        endTime: "" // 结束时间
      },
      loaded: false
    };
  },
  computed: {},
  created() {
    let orgInfo = this.$A.GS("orgInfo");
    this.org.res = [
      { label: orgInfo.orgName, value: orgInfo.orgId, type: orgInfo.type }
    ];
    // this.params.orgId = orgInfo.orgId;
    // this.params.type = orgInfo.type;
    this.currOrg = orgInfo.orgName;
    this.params.startTime = Util.timeForMat(30)[0].substr(0, 10);
    this.params.endTime = Util.timeForMat(30)[1].substr(0, 10);
  },
  mounted() {
    this.$nextTick(() => {
      this.getData();
    });
  },
  watch: {},
  methods: {
    tabStatus() {
      // 数据处理
      this.getData();
    },
    getData() {
      this.loaded = false;
      this.$openLoading();
      this.chart && this.chart.destroy();
      let api = "";
      if (this.active == 1) {
        this.params.orgId = this.org.res[0].value;
        this.params.type = this.org.res[0].type;
        api = this.api.getObsDataApi;
      } else {
        this.params.orgId = this.$A.GS("orgInfo").orgId;
        this.params.type = this.$A.GS("orgInfo").type;
        api = this.api.getIssRepoDataApi;
      }
      this.$A
        .Go("get", api, this.params)
        .then(response => {
          this.$closeLoading();
          this.loaded = true;
          Util.processRes(response, () => {
            this.chartData = response.body;
            if (this.chartData.length) {
              this.init();
            }
          });
          Util.processError(this, response);
        })
        .catch(err => {
          this.loaded = true;
          this.$closeLoading();
          console.log(err);
        });
    },
    open() {
      this.org.open = true;
    },
    close() {
      this.org.open = false;
    },
    confirm() {
      this.params.orgId = this.org.res[0].value;
      this.currOrg = this.org.res[0].label;
      this.getData();
      this.org.open = false;
    },
    init() {
      const map = {};
      let allN = 0;
      this.chartData.forEach(obj => {
        allN += isNaN(Number(obj.value))?0:Number(obj.value);
      })
      this.chartData.forEach(obj => {
        obj.a = "1";
        obj.rate = Number(isNaN(Number(obj.value))?0:parseFloat((Number(obj.value)/allN)*100).toFixed(2));
        map[obj.name] = obj.rate + "%";
        map[obj.name+'value'] = obj.value;
      });
      this.chart = new F2.Chart({
        id: "container",
        plugins: PieLabel,
        pixelRatio: window.devicePixelRatio,
        height:500,
        padding: ["auto", 80]
      });
      console.log(this.chartData)
      this.chart.source(this.chartData, {
        rate: {
          formatter: function formatter(val) {
            return val + "%";
          }
        }
      });
      this.chart.tooltip(false);
      this.chart.legend({
        position: "bottom",
        marker: {
          symbol: "square" // marker 的形状
        },
        itemFormatter: function itemFormatter(val) {
          console.log(val)
          console.log(map)
          return val + "    " + map[val] +  "    " + map[val+'value'] + '次';
        },
        titleStyle: {
          textAlign: "start", // 文本对齐方向，可取值为： start middle end
          fill: "#8C8C8C", // 文本的颜色
          fontSize: 12, // 文本大小
          textBaseline: "bottom" // 文本基准线，可取 top middle bottom，默认为middle
        }
      });
      this.chart.pieLabel({
        sidePadding: 30,
        activeShape: true,
        label1: function label1(data) {
          return {
            text: data.rate + "%",
            fill: "#343434",
            fontWeight: "bold"
          };
        }
      });
      // console.log(this.chart);

      this.chart.coord("polar", {
        transposed: true,
        innerRadius: 0.7,
        radius: 0.85
      });
      this.chart.axis(false);
      this.chart
        .interval()
        .position("a*rate")
        .color("name")
        .adjust("stack");
      /*if (this.active == '1') {
          this.chart.guide().html({
            position: ['50%', '45%'],
            html: `<div style="width: 2.5rem;height: .4rem;text-align: center;">
                  <div style="font-size: 0.41rem">52</div>
                  <div style="font-size: 0.13rem">行为观察</div>
                </div>`
          });
        } else {
          this.chart.guide().html({
            position: ['50%', '45%'],
            html: `<div style="width: 2.5rem;height: .4rem;text-align: center;">
                  <div style="font-size: 0.41rem">52</div>
                  <div style="font-size: 0.13rem">问题上报</div>
                </div>`
          });
        }*/

      this.chart.render();
    },
    //不可选择的开始日期
    disabledStartDates(date) {
      if (this.params.endTime) {
        return date.getTime() > new Date(this.params.endTime).getTime();
      } else {
        return false;
      }
    },
    //不可选择的结束日期
    disabledEndDates(date) {
      if (this.params.startTime) {
        return date.getTime() <= new Date(this.params.startTime).getTime();
      } else {
        return false;
      }
    }
  },
  destroyed() {}
};
</script>

<style lang="scss">
.select-box {
  padding: 0 14px;
  background: #fff;
  .org-select {
    margin-top: 0.1rem;
    display: inline-block;
    padding: 0.08rem 0.12rem;
    background: rgba(248, 248, 248, 1);
    border-radius: 0.02rem;
    font-size: 0.12rem;
    font-weight: 500;
    color: #3d3d3d;
    line-height: 0.17rem;
  }
  .date-select {
    margin-top: 0.1rem;
    padding: 0.08rem 0.12rem;
    background: rgba(248, 248, 248, 1);
    border-radius: 0.02rem;
    font-size: 0.12rem;
    color: #3d3d3d;
    min-height: 0;
    line-height: 0.17rem;
    .mu-text-field {
      height: 0.17rem;
    }
  }
}
#container {
  width: 100%;
  height: 80%;
}
</style>
